package com.lmc.chatroom.config;

import com.lmc.chatroom.constant.constant;
import com.lmc.chatroom.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        1.获取token
        String token = request.getHeader(constant.USER_TOKEN_HEADER);
        log.info("拦截器："+token);
//        2.校验token
        Boolean flag = JwtUtil.checkToken(token);
        if (flag) {
            log.info("token正确，放行");
            return true;
        }else{
//        3.错误则设置错误状态码
            log.info("token有误，不予放行");
            response.setStatus(401);
        }
        return false;
    }
}
